package com.darker.secking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.darker.secking.entity.*;
import com.darker.secking.exception.GlobalException;
import com.darker.secking.mapper.OrderMapper;
import com.darker.secking.service.IGoodsService;
import com.darker.secking.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.darker.secking.service.ISeckingGoodsService;
import com.darker.secking.service.ISeckingOrderService;
import com.darker.secking.utils.MD5Util;
import com.darker.secking.vo.DetailVo;
import com.darker.secking.vo.GoodsVo;
import com.darker.secking.vo.OrderDetailVo;
import com.darker.secking.vo.RespBeanEnum;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author darker
 * @since 2022-10-06
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckingGoodsService seckingGoodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISeckingOrderService seckingOrderService;
    @Autowired
    IGoodsService goodsService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public OrderDetailVo findDetail(Long orderId) {


        Order order = orderMapper.selectById(orderId);

        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrder(order);
        GoodsVo goods = goodsService.findGoodsById(order.getGoodsId());
        orderDetailVo.setGoodsVo(goods);

        return orderDetailVo;
    }

    @Override
    public String createPath(User user, Long goodsId) {
        if(user==null||goodsId<0){
            return null;
        }


        //生成加密的路径
        String str = MD5Util.md5(UUID.randomUUID()+"123456");
        //存入redis中
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+":"+goodsId,str,1, TimeUnit.MINUTES);
        return str;
    }


    //校验验证码
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (null == user || goodsId < 0||StringUtils.isEmpty(captcha)) {
           return false;
        }


        String redisCaptcha = redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId).toString();


        return redisCaptcha.equals(captcha);
    }

    //校验秒杀路径
    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {
        if(user==null||goodsId<0|| StringUtils.isEmpty(path)){
            return false;
        }

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String redisPath = valueOperations.get("seckillPath:" + user.getId() + ":" + goodsId).toString();

        return path.equals(redisPath);
    }

    //    创建秒杀订单
    @Override
    @Transactional
    public Order secking(User user, GoodsVo goods) {
        //根据商品id查询秒杀的商品
        LambdaQueryWrapper<SeckingGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeckingGoods::getGoodsId, goods.getId());
        SeckingGoods seckingGoods = seckingGoodsService.getOne(queryWrapper);

        //        秒杀商品表减库存
        LambdaUpdateWrapper<SeckingGoods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("stock_count=stock_count-1")
                .eq(SeckingGoods::getGoodsId,seckingGoods.getGoodsId())
                .gt(SeckingGoods::getStockCount,0);
        boolean update = seckingGoodsService.update(updateWrapper);
//        判断是否更新库存成功 不成功则是没有库存
        if (!update) {
        redisTemplate.opsForValue().set("isStockEmpty:"+goods.getId(),"0");
       return null;
        }

//        生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0l);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckingGoods.getSeckingPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(LocalDateTime.now());
        orderMapper.insert(order);

        //生成秒杀订单
        SeckingOrder seckingOrder = new SeckingOrder();
        seckingOrder.setGoodsId(goods.getId());
        seckingOrder.setUserId(user.getId());
        seckingOrder.setOrderId(order.getId());
        seckingOrderService.save(seckingOrder);

        redisTemplate.opsForValue().set("order:" + user.getId() + ":" + goods.getId(), seckingOrder);


        return order;
    }
}
